package com.itheima.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class LoginFilter extends ZuulFilter {
    @Override
    public String filterType() {
//        代表为前置拦截
//        - pre：请求在被路由之前执行
//        - routing：在路由请求时调用
//        - post：在routing和errror过滤器之后调用
//        - error：处理请求时发生错误调用
        return "pre";
    }

    @Override
    public int filterOrder() {
//        过滤顺序为1
        return 1;
    }

    @Override
    public boolean shouldFilter() {
//        true表示过滤器生效
        return true;
    }

    @Override
    public Object run() throws ZuulException {
//        获取Zuul提供的资源管理器对象
        RequestContext requestContext = RequestContext.getCurrentContext();
//        从资源管理器中获取request对象
        HttpServletRequest request = requestContext.getRequest();
//        从请求中获取paizi参数
        String paizi = request.getParameter("paizi");

        if (StringUtils.isEmpty(paizi)){
//            paizi属性为空则拦截
            requestContext.setSendZuulResponse(false);
//            返回一个状态码
            requestContext.setResponseStatusCode(401);
        }

        return null;
    }
}
